package com.wu.service.impl;

import com.wu.pojo.model.UserToken;
import com.wu.service.LikeArticleService;
import com.wu.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

import static com.wu.constant.Constant.*;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-30 00:21
 */
@Service
public class LikeArticleServiceImpl implements LikeArticleService {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    @Transactional
    public Map<Object, Object> addOrDeleteLike(String articleId) {
        HashMap<Object, Object> map = new HashMap<>();
        UserToken userToken = tokenUtils.parseTokenToUserToken();
        //获取用户ID
        String userId = userToken.getUserId();

        //直接替换原来的数据库存储
        if (redisTemplate.opsForSet().isMember(userId + _ARTICLE_UP, articleId)) {
            //说明用户已经点赞，现在是取消点赞请求
            redisTemplate.opsForValue().decrement(articleId + _ARTICLE_UP_COUNT);
            redisTemplate.opsForSet().remove(userId + _ARTICLE_UP, articleId);
            redisTemplate.opsForSet().remove(articleId + _ARTICLE_UP_USER, userId);
            redisTemplate.opsForValue().decrement(userId + _UP_COUNT);
        } else {
            redisTemplate.opsForValue().increment(articleId + _ARTICLE_UP_COUNT);
            redisTemplate.opsForSet().add(userId + _ARTICLE_UP, articleId);
            redisTemplate.opsForSet().add(articleId + _ARTICLE_UP_USER, userId);
            redisTemplate.opsForValue().increment(userId + _UP_COUNT);
        }
        map.put(COUNT, redisTemplate.opsForValue().get(articleId + _ARTICLE_UP_COUNT));
        return map;
    }
}
